<template>
  <vxe-modal
    v-model="dialogFormVisible"
    :title="title"
    show-footer
    transfer
    fullscreen
    destroy-on-close
    :loading="listLoading"
    @close="close"
  >
    <template #default>
      <el-container style="border: 1px solid #aed0ea">
        <el-main style="border-right: 1px solid rgb(174, 208, 234)">
          <vxe-form
            ref="formRef"
            :data="form"
            :rules="rules"
            title-align="right"
            title-width="120"
            prevent-submit
            custom-layout
          >
            <vxe-form-item title="角色编码" field="code" span="24">
              <template #default>
                <el-input v-model="form.code" placeholder="角色编码" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="角色名称" span="24" field="name">
              <template #default>
                <el-input v-model="form.name" placeholder="请输入角色名称" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="状态" span="24" field="status">
              <template #default>
                <el-switch
                  v-model="form.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="0"
                  :inactive-value="1"
                />
              </template>
            </vxe-form-item>
            <vxe-form-item title="类型" span="24" field="sort">
              <template #default>
                <el-radio-group v-model="form.type">
                  <el-radio-button
                    v-for="item in roleTypes"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-radio-group>
              </template>
            </vxe-form-item>
            <vxe-form-item title="排序" span="24" field="sort">
              <template #default>
                <el-input-number
                  v-model="form.sort"
                  controls-position="right"
                  :min="1"
                  :max="1000"
                  :placeholder="'请输入排序'"
                  style="width: 160px"
                />
              </template>
            </vxe-form-item>
            <vxe-form-item title="备注" span="24" field="remarks">
              <template #default>
                <el-input
                  v-model="form.remarks"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder="备注"
                />
              </template>
            </vxe-form-item>
          </vxe-form>
        </el-main>
        <el-aside style="background-color: #fff" width="550px">
          <div class="tree-container">
            <el-scrollbar class="x-scrollbar" style="height: 100%">
              <el-tree
                ref="treeRef"
                :data="list"
                show-checkbox
                node-key="id"
                highlight-current
                :default-checked-keys="defaultCheckedKeysMenu"
                :props="{
                  children: 'children',
                  label: 'name',
                }"
              />
            </el-scrollbar>
          </div>
        </el-aside>
      </el-container>
    </template>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <el-button type="primary" :loading="subListLoading" @click="save">
          <i class="icon-wpkj-save"></i>
          确定
        </el-button>
        <el-button type="danger" @click="close">取消</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script>
  import { Finished } from '@element-plus/icons-vue'
  import { getAddRole, getRole, saveOrUpdate } from '@/api/system/role'

  export default defineComponent({
    name: 'PreviewCode',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const $XEUtils = inject('$XEUtils')
      const state = reactive({
        formRef: null,
        treeRef: null,
        listLoading: false,
        subListLoading: false,
        form: {
          code: '',
          name: '',
          type: '',
          status: 0,
          sort: 0,
          remark: '',
        },
        rules: {
          code: [
            { required: true, message: '请输入编码', trigger: 'blur' },
            {
              min: 1,
              max: 100,
              message: '长度在 1 到 100 个字符',
              trigger: 'blur',
            },
          ],
          name: [
            { required: true, message: '请输入角色名', trigger: 'blur' },
            {
              min: 1,
              max: 100,
              message: '长度在 1 到 100 个字符',
              trigger: 'blur',
            },
          ],
          sort: [
            {
              required: true,
              message: '请输入排序',
              trigger: 'blur',
            },
          ],
        },
        title: '',
        dialogFormVisible: false,
        list: [],
        roleTypes: [],
        defaultCheckedKeysMenu: [],
      })

      const showEdit = async (row) => {
        state.dialogFormVisible = true
        state.listLoading = true
        if (!row) {
          state.title = '添加'
          const { code, data, msg } = await getAddRole().catch((err) => {
            state.listLoading = false
          })
          if (code === 0 || code === 200) {
            state.form.sort = data.sort
            state.roleTypes = data.dict
            state.list = $XEUtils.toArrayTree(data.menu, {
              key: 'id',
              parentKey: 'parentId',
            })
          } else {
            $baseMessage(msg, 'error', 'vab-hey-message-success')
          }
        } else {
          state.title = '编辑'
          const { code, data, msg } = await getRole(row.id).catch((err) => {
            state.listLoading = false
          })
          if (code === 0 || code === 200) {
            state.form = data.role
            state.roleTypes = data.dict
            state.list = $XEUtils.toArrayTree(data.menu, {
              key: 'id',
              parentKey: 'parentId',
            })
            state.defaultCheckedKeysMenu = data.permission
          } else {
            $baseMessage(msg, 'error', 'vab-hey-message-success')
          }
        }
        state.listLoading = false
      }
      const close = () => {
        state['formRef'].reset()
        state.form = {
          code: '',
          name: '',
          type: '',
          status: null,
          sort: null,
          remark: '',
        }
        state.list = []
        state.defaultCheckedKeysMenu = []
        state.dialogFormVisible = false
        state.listLoading = false
        state.subListLoading = false
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (!valid) {
            if (state['treeRef'].getCheckedKeys(true).length > 0) {
              state.subListLoading = true
              const roleMenu = `${state['treeRef']
                .getCheckedKeys(true)
                .join(',')},${state['treeRef'].getCheckedKeys(false).join(',')}`
              const { code, msg, data } = await saveOrUpdate({
                roleDO: state.form,
                roleMenuDOList: roleMenu.split(','),
              }).catch((err) => {
                state.subListLoading = false
              })
              if (code === 0 || code === 200) {
                emit('fetch-data')
                close()
              } else {
                $baseMessage(message, 'error', 'vab-hey-message-success')
              }
            } else {
              $baseMessage('请选择右边权限', 'error', 'vab-hey-message-success')
            }
          }
        })
      }
      onMounted(() => {})
      return {
        ...toRefs(state),
        Finished,
        showEdit,
        close,
        save,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    width: 100%;
    height: 250px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }

  .el-container {
    height: calc(100vh - 155px);
  }
</style>
